package com.foxit.pdf2html5.web.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.foxit.pdf2html5.web.common.Config;
import com.google.gson.Gson;

import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudHttpKey;
import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudHttpState;
import com.foxit.pdf2html5.web.foxitcloud.iterface.realization.FoxitCloudIterfaceImp;

public class FoxitCloudUtils {
	private static final Logger logger = Logger.getLogger(FoxitCloudUtils.class);
	/**
	 * save document and generate an GUID for the document.
	 * 
	 * @param resultParams return id and name of the document.
	 * @param request HTTP request object.
	 * @return return true if save file successfully, otherwise return false.
	 */
	public static boolean saveUploadedFile(String userId,HashMap<String,String> map,InputStream inStream,String fileName) {
		try {
			// userId
			boolean boolean_upload = false;
			HashMap tokenMap = FoxitCloudIterfaceImp.getToken(userId);
			if(tokenMap == null){
				logger.error("saveUploadedFile method tokenMap is null");
				map.put("error", FoxitCloudHttpState.HTTP_UPLOAD_BLOCK_ERROR+"");
				return false;
			}
			Double tokenRet = (Double)tokenMap.get(FoxitCloudHttpKey.RET);
			if(tokenRet != FoxitCloudHttpState.HTTP_SUCCESS){
				logger.error("get token error:ret = "+tokenRet);
				map.put("error", tokenRet+"");
				return false;
			}
			String token = (String)tokenMap.get(FoxitCloudHttpKey.TOKEN);
			
			if(token == null || "".equals(token)){
				logger.error("get token error:ret = "+tokenRet);
				map.put("error", tokenRet+"");
				return false;
			}
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
		    byte[] buff = new byte[1024];  
		    int rc = 0;  
		    while ((rc = inStream.read(buff, 0, 100)) > 0) {  
		       swapStream.write(buff, 0, rc);  
		    }  
		    byte[] data = swapStream.toByteArray();
		    long maxUploadFileSize = Config.DEFAULT_DEMO_SITE_MAX_UPLOAD_FILE_SIZE;
		    int dataLength = data.length;
		    if(dataLength > (maxUploadFileSize * 1024 * 1024)){
		    	logger.error("The document size is larger than the maximum value");
				map.put("error", FoxitCloudHttpState.HTTP_UPLOAD_BLOCK_ERROR+"");
				return false;
		    }
		    
		    String fileHash = HashUtil.getMd5Sha1Hash(data);
		    HashMap blockMap = FoxitCloudIterfaceImp.getBlockInfo(token, fileName, data, fileHash);
		    String docId = "";
		    while(true){
				if(blockMap == null){
					logger.error("Failed to upload files");
					map.put("error", FoxitCloudHttpState.HTTP_UPLOAD_BLOCK_ERROR+"");
					return false;
				}
				Double retBlock = (Double)blockMap.get(FoxitCloudHttpKey.RET); 
				if(retBlock == FoxitCloudHttpState.HTTP_SUCCESS_NOT_UPLOAD_BLOCKS){
					docId = blockMap.get(FoxitCloudHttpKey.DOCID)+"";
					
					logger.info("The file has been uploaded successfully. ret = :"+retBlock);
					map.put("docId", docId);
					map.put("token", token);
					map.put("fileName", fileName);
					map.put("error", "");
					return true;
				}
				if(retBlock != FoxitCloudHttpState.HTTP_SUCCESS){
					logger.error("Failed to upload files.ret = "+retBlock);
					map.put("error", retBlock+"");
					return false;
				}
				blockMap = FoxitCloudIterfaceImp.uploadBlock(blockMap, token, fileName, data,fileHash);
		    }
		} catch (Exception e) {
			logger.error("Failed to upload files");
			return false;
		}
	}

	/** return error code to client.
	 * @param response HTTP response object.
	 * @param errorInfo error information.
	 * @throws IOException
	 */
	public static void setErrorResponse(HttpServletResponse response,HashMap<String, String> map) throws IOException
	{
		Gson gson = new Gson();
		response.getWriter().write(gson.toJson(map).toString());
	}
}
